package com.adopapa.nezhacloud.authc.service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.adopapa.nezhacloud.authc.conf.AuthcConstants;
import com.adopapa.nezhacloud.authc.domain.LoginUser;
import com.adopapa.nezhacloud.authc.utils.JwtUtils;
import com.adopapa.nezhacloud.common.SecurityConstants;
import com.adopapa.nezhacloud.common.Tools;
import com.adopapa.nezhacloud.common.UuidUtils;
import com.adopapa.nezhacloud.ddd.service.BaseService;
import com.adopapa.nezhacloud.redis.RedisService;

import jakarta.servlet.http.HttpServletRequest;

@Component
public class TokenService extends BaseService {

	@Autowired
	private RedisService redisService;

	protected final static long MILLIS_SECOND = 1000L;

	protected final static long MILLIS_MINUTE = 60 * MILLIS_SECOND;

	/**
	 * 缓存有效期，默认720（分钟）
	 */
	private final static long EXPIRE_TIME = 720L;

//	private final static String ACCESS_TOKEN = "login_tokens:";

	private final static Long MILLIS_MINUTE_TEN = 120L * MILLIS_MINUTE;

	/**
	 * 创建令牌
	 */
	public Map<String, Object> createToken(LoginUser loginUser) {
		String token = UuidUtils.fastUUID();
		String userId = loginUser.getUserId();
		String userName = loginUser.getUserName();
//		String ipAddr = loginUser.getIpAddr();
//		loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
		loginUser.setToken(token);
		// 保存到缓存中
		refreshToken(loginUser);

		// Jwt存储信息
		Map<String, Object> claimsMap = new HashMap<String, Object>();
		claimsMap.put(SecurityConstants.USER_KEY, token);
		claimsMap.put(SecurityConstants.USER_ID, userId);
		claimsMap.put(SecurityConstants.USER_NAME, userName);

		// 接口返回信息
		Map<String, Object> respMap = new HashMap<String, Object>();
		respMap.put("access_token", JwtUtils.createToken(claimsMap));
		respMap.put("expires_in", EXPIRE_TIME);
		return respMap;
	}

	/**
	 * 获取用户身份信息
	 *
	 * @return 用户信息
	 */
	public LoginUser getLoginUser(HttpServletRequest request) {
		// 获取请求携带的令牌
		String token = request.getHeader(AuthcConstants.AUTHENTICATION);
		return getLoginUser(token);
	}

	/**
	 * 获取用户身份信息
	 *
	 * @return 用户信息
	 */
	public LoginUser getLoginUser(String token) {
		LoginUser user = null;
		try {
			if (!Tools.empty(token)) {
				String userkey = JwtUtils.getUserKey(token);
				RedisTemplate<String, Object> redisTemplate = //
						redisService.getRedisTemplate(AuthcConstants.AUTHC_REDIS_DBINDEX);
				user = (LoginUser) redisTemplate.opsForValue().get(JwtUtils.getTokenKey(userkey));
				return user;
			}
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}
		return user;
	}

	/**
	 * 设置用户身份信息
	 */
	public void setLoginUser(LoginUser loginUser) {
		if (!Tools.empty(loginUser) && !Tools.empty(loginUser.getToken())) {
			refreshToken(loginUser);
		}
	}

	/**
	 * 删除用户缓存信息
	 */
	public void delLoginUser(String token) {
		if (!Tools.empty(token)) {
			String userkey = JwtUtils.getUserKey(token);
			RedisTemplate<String, Object> redisTemplate = //
					redisService.getRedisTemplate(AuthcConstants.AUTHC_REDIS_DBINDEX);
			redisTemplate.delete(JwtUtils.getTokenKey(userkey));
		}
	}

	/**
	 * 验证令牌有效期，相差不足120分钟，自动刷新缓存
	 *
	 * @param loginUser
	 */
	public void verifyToken(LoginUser loginUser) {
		long expireTime = loginUser.getExpireTime();
		long currentTime = System.currentTimeMillis();
		if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
			refreshToken(loginUser);
		}
	}

	/**
	 * 刷新令牌有效期
	 *
	 * @param loginUser 登录信息
	 */
	public void refreshToken(LoginUser loginUser) {
		loginUser.setLoginTime(System.currentTimeMillis());
		loginUser.setExpireTime(loginUser.getLoginTime() + EXPIRE_TIME * MILLIS_MINUTE);
		// 根据uuid将loginUser缓存
		String userKey = JwtUtils.getTokenKey(loginUser.getToken());
		RedisTemplate<String, Object> redisTemplate = //
				redisService.getRedisTemplate(AuthcConstants.AUTHC_REDIS_DBINDEX);
		redisTemplate.opsForValue().set(userKey, loginUser, EXPIRE_TIME, TimeUnit.MINUTES);
	}

}